from dashscope.api_entities.dashscope_response import DashScopeAPIResponse
from dashscope.client.base_api import BaseAsyncApi
from code.app.services.api_response import APIResponse
from code.app.enum.enums import ModelAPISetting
from code.app.utils.object_utils import convert_to_dict
import os

# 本地调试可以通过设置环境变量来配置参数，也可以在代码中直接设置（有安全风险，不推荐）。
# 在百炼平台查看我的API-KEY（https://bailian.console.aliyun.com/?apiKey=1#/api-key），本地测试可填写主账号API-KEY。
# 环境变量配置方式参考：https://help.aliyun.com/zh/model-studio/developer-reference/configure-api-key-through-environment-variables?spm=a2c4g.11186623.help-menu-2400256.d_3_1.3d077becSWI3Ks#04beb8092b70d
api_key = os.getenv("DASHSCOPE_API_KEY")


class APICall(BaseAsyncApi):
    """接口调用公共类
    """

    @classmethod
    def async_call(cls,
                   model: str,
                   workspace: str = None,
                   input: dict = None,
                   parameters: dict = None,
                   **kwargs) -> APIResponse:
        """异步调用

        参数：
            model: 模型名称如，如 wanx-style-repaint-v1
            workspace：业务空间ID。如果api_key使用主账号，则不需要填写，如果api_key使用子账号，需要填写百炼平台上子账号对应的业务空间ID。
                       获取业务空间ID：https://help.aliyun.com/zh/model-studio/developer-reference/use-workspace?spm=a2c4g.11186623.0.0.99183fc3fLVhTb#c5222ec081sbo
            input: 根据模型而定，与HTTP调用的请求结构保持一致，如人像风格重绘 https://help.aliyun.com/zh/model-studio/developer-reference/portrait-style-redraw-api-reference?spm=a2c4g.11186623.help-menu-2400256.d_3_3_3_1.682f3fc3BUjiSY
            parameters: 同 input 参数，根据模型而定，与HTTP调用的请求结构保持一致。

        返回：
            APIResponse: 将异步调用结果封装成 APIResponse 对象

        """
        kwargs.pop('parameters', {})
        if parameters is not None:
            kwargs = convert_to_dict(parameters)

        model_api_setting = ModelAPISetting.from_model(model)
        task_group = model_api_setting.task_group
        task = model_api_setting.task
        function = model_api_setting.function

        # 复用阿里云百炼 dashcope sdk 的 async_call 方法
        response = super().async_call(
            model=model,
            task_group=task_group,
            task=task,
            function=function,
            api_key=api_key,
            input=input,
            workspace=workspace,
            **kwargs)

        return APIResponse.from_api_response(response)

    @classmethod
    def call(cls,
             model: str,
             workspace: str = None,
             input: dict = None,
             parameters: dict = None,
             **kwargs) -> DashScopeAPIResponse:
        kwargs.pop('parameters', {})
        if parameters is not None:
            kwargs = convert_to_dict(parameters)

        model_api_setting = ModelAPISetting.from_model(model)

        # 复用阿里云百炼 dashcope sdk 的 call 方法
        response = super().call(model=model,
                                task_group=model_api_setting.task_group,
                                task=model_api_setting.task,
                                function=model_api_setting.function,
                                input=input,
                                api_key=api_key,
                                workspace=workspace,
                                **kwargs)

        return APIResponse.from_api_response(response)

    @classmethod
    def get_result(cls,
                   task_id: str,
                   workspace: str = None) -> APIResponse:
        # 复用阿里云百炼 dashcope sdk 的 get_result 方法
        response = super()._get(task_id=task_id,
                                api_key=api_key,
                                workspace=workspace)
        return APIResponse.from_api_response(response)
